<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { queryCategories } from '@/service/category.js'
import { ElTreeSelect } from 'element-plus'
import PlusIcon from '@/components/icons/PlusIcon.vue'
import { changeProductStatus, deleteProduct, queryProductListOptimized } from '@/service/product.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Bottom, Delete, Top } from '@element-plus/icons-vue'
const router = useRouter()
const productList = ref([])
const totalRecords = ref(0)
const searchForm = reactive({
  productName: null,
  brandName: null,
  productId: null,
  categoryId: -1,
  productType: -1,
  productStatus: -1,
  currentPage: 1,
  pageSize: 10,
})
async function loadData() {
  const res = await queryProductListOptimized(
    searchForm.productName,
    searchForm.brandName,
    searchForm.productType === -1 ? null : searchForm.productType,
    searchForm.productId,
    searchForm.categoryId === -1 ? null : searchForm.categoryId,
    searchForm.productStatus === -1 ? null : searchForm.productStatus,
    searchForm.currentPage,
    searchForm.pageSize
  )
  console.log(res)
  productList.value = res.data.records
  totalRecords.value = res.data.total
}
watch(
  searchForm,
  async () => {
    await loadData()
  },
  { immediate: true }
)
const categoryList = ref([])
onMounted(() => {
  queryCategories().then((res) => {
    categoryList.value = res.data
    categoryList.value.unshift({ id: -1, name: '全部分类' })
  })
})
function createCommodity() {
  router.push({ name: 'addProduct' })
}
function onTapEditButton(row) {
  router.push({
    name: 'editProduct',
    params: {
      id: row.productId,
    },
  })
}
function onTapDeleteButton(row) {
  ElMessageBox.confirm(`确定删除商品：<span style="color: red">${row.productName}</span>?`, '信息', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true, // 允许内容使用 HTML 字符串
  })
    .then(async () => {
      await deleteProduct(row.productId)
      await loadData()
      ElMessage({
        type: 'success',
        message: '成功删除商品！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const showOperationButtons = ref(false)
const productTableRef = ref()
function onTapBatchShelveButton() {
  const productIds = productTableRef.value.getSelectionRows().map((item) => item.productId)
  ElMessageBox.confirm('您确定要上架所选商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success',
    draggable: true,
  })
    .then(async () => {
      if (!productIds.length) return
      let promiseArray = []
      for (let i = 0; i < productIds.length; i++) {
        promiseArray.push(changeProductStatus(productIds[i], 0))
      }
      await Promise.all(promiseArray)
      await loadData()
      ElMessage({
        type: 'success',
        message: '成功上架所选商品！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消上架',
      })
    })
}
function onTapBatchTakeDownButton() {
  const productIds = productTableRef.value.getSelectionRows().map((item) => item.productId)
  ElMessageBox.confirm('您确定要下架所选商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  })
    .then(async () => {
      if (!productIds.length) return
      let promiseArray = []
      for (let i = 0; i < productIds.length; i++) {
        promiseArray.push(changeProductStatus(productIds[i], 1))
      }
      await Promise.all(promiseArray)
      await loadData()
      ElMessage({
        type: 'success',
        message: '成功下架所选商品！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消下架',
      })
    })
}
function onTapBatchDeleteButton() {
  const productIds = productTableRef.value.getSelectionRows().map((item) => item.productId)
  ElMessageBox.confirm('您确定要删除所选商品吗？此操作不可恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
    draggable: true,
  })
    .then(async () => {
      if (!productIds.length) return
      let promiseArray = []
      for (let i = 0; i < productIds.length; i++) {
        promiseArray.push(deleteProduct(productIds[i]))
      }
      await Promise.all(promiseArray)
      await loadData()
      ElMessage({
        type: 'success',
        message: '成功删除所选商品！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
function handleSelectionChange(event) {
  showOperationButtons.value = event && event.length > 0
}
</script>

<template>
  <div class="product">
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="商品名称:" style="width: 250px">
        <el-input v-model="searchForm.productName" placeholder="请问输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品编码:" style="width: 250px">
        <el-input-number
          v-model="searchForm.productId"
          :controls="false"
          :precision="0"
          align="left"
          placeholder="请问输入商品编码"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="商品类型:" style="width: 250px">
        <el-select v-model="searchForm.productType" placeholder="Select" style="width: 240px">
          <el-option :value="-1" label="全部类型" />
          <el-option :value="0" label="普通商品" />
          <el-option :value="1" label="秒杀商品" />
          <el-option :value="2" label="临期特惠商品" />
          <el-option :value="3" label="新客专享商品" />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌名称:" style="width: 250px">
        <el-input v-model="searchForm.brandName" placeholder="请问输入商品品牌名称"></el-input>
      </el-form-item>
      <el-form-item label="商品分类:">
        <el-tree-select
          v-model="searchForm.categoryId"
          :data="categoryList"
          :props="{
            label: 'name',
            children: 'children',
          }"
          :render-after-expand="true"
          check-strictly
          style="width: 200px"
          value-key="id"
        />
        <el-button style="margin-left: 20px" type="warning">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="product-status">
      <el-tabs v-model="searchForm.productStatus" stretch type="card">
        <el-tab-pane :name="-1" label="全部"></el-tab-pane>
        <el-tab-pane :name="0" label="出售中"></el-tab-pane>
        <el-tab-pane :name="1" label="已下架"></el-tab-pane>
        <el-tab-pane :name="2" label="已售罄"></el-tab-pane>
      </el-tabs>
      <el-button style="margin-left: 10px" type="primary" @click="createCommodity">
        <el-icon size="20">
          <PlusIcon />
        </el-icon>
        创建商品
      </el-button>
      <el-button-group v-if="showOperationButtons" style="margin-left: 10px">
        <el-button type="default" :icon="Top" @click="onTapBatchShelveButton">上架</el-button>
        <el-button type="default" :icon="Bottom" @click="onTapBatchTakeDownButton">下架</el-button>
        <el-button type="default" :icon="Delete" @click="onTapBatchDeleteButton">删除</el-button>
      </el-button-group>
    </div>
    <el-table
      :data="productList"
      :header-cell-style="() => ({ background: '#eef1f6', color: '#606266' })"
      border
      @selection-change="handleSelectionChange"
      ref="productTableRef"
      style="width: 100%; margin: 10px 0"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="商品编号" width="100">
        <template #default="scope">
          <div>{{ scope.row.productId }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品图片" width="100">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <el-image :src="scope.row.productImage" show-progress style="width: 50px; height: 50px" />
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品名称" width="200">
        <template #default="scope">
          <div class="product-name">{{ scope.row.productName }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品价格" width="120">
        <template #default="scope">
          <div v-if="scope.row.minPrice === scope.row.maxPrice">￥{{ scope.row.minPrice }}</div>
          <div v-else>￥{{ scope.row.minPrice }}~￥{{ scope.row.maxPrice }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="总销量" width="100">
        <template #default="scope">
          <div class="product-name">{{ scope.row.saleCount }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="库存总量" width="100">
        <template #default="scope">
          <div class="product-name">{{ scope.row.stock }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.productStatus === 0" type="success">上架中</el-tag>
          <el-tag v-if="scope.row.productStatus === 1" type="danger">下架中</el-tag>
          <el-tag v-if="scope.row.productStatus === 2" type="warning">已售罄</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="权重">
        <template #default="scope">
          <div>{{ scope.row.weight }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品类型" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.productType === 0" effect="plain" type="primary">普通商品</el-tag>
          <el-tag v-if="scope.row.productType === 1" effect="plain" type="danger">秒杀商品</el-tag>
          <el-tag v-if="scope.row.productType === 2" effect="plain" type="info">临期特惠</el-tag>
          <el-tag v-if="scope.row.productType === 3" effect="plain" type="success">新客专享</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="175">
        <template #default="scope">
          <div>{{ scope.row.createTime }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间" width="175">
        <template #default="scope">
          <div>{{ scope.row.updateTime }}</div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="170">
        <template #default="scope">
          <el-button type="primary" @click="onTapEditButton(scope.row)">编辑</el-button>
          <el-button type="danger" @click="onTapDeleteButton(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="searchForm.currentPage"
      v-model:page-size="searchForm.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :total="totalRecords"
      layout="total, sizes, prev, pager, next, jumper"
    />
  </div>
</template>

<style lang="scss" scoped>
.product {
  background-color: #fff;
  padding: 20px;
}
.product-status {
  display: flex;
  align-items: center;
  :deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
    border-bottom: 1px solid transparent;
  }
  :deep(.el-tabs__header) {
    margin: 0;
  }
  :deep(.el-tabs__item.is-top) {
    font-size: 14px;
    padding: 0 15px;
  }
  .el-tabs {
    --el-tabs-header-height: 32px;
  }
}
.product-name {
  display: -webkit-box; /* 弹性盒模型，用于多行文本截断 */
  -webkit-line-clamp: 2; /* 限制显示的行数 */
  -webkit-box-orient: vertical; /* 文本垂直排列 */
  overflow: hidden; /* 溢出隐藏 */
  text-overflow: ellipsis; /* 溢出部分显示省略号 */
}
</style>
